from django.conf.urls.defaults import url

def section(name, menu_name, page_title, prefix, *actions):
    section = SectionManager(name, menu_name, page_title)
    
    for a in actions:
        a.set_view_prefix(prefix)
        section.add_action(a)
        
    return section

def action(name, view, page_title, menu_name=None, regex=False, is_index=False):
    if not regex:
        regex = r'^%s/$' % name
    
    action = ActionManager(name, view, page_title, menu_name, regex, is_index)
    
    return action

class ActionManager:
    def __init__(self, name, view, page_title, menu_name, regex, is_index):
        self.name = name
        self.view = view
        self.page_title = page_title
        self.menu_name = menu_name
        self.regex = regex
        self.is_index = is_index
    
    def set_view_prefix(self, prefix):
        if prefix:
            self.view = '%s.%s' % (prefix, self.view)
        
    def set_section(self, section):
        self.section = section
        
        self.regex = r'^%s/%s' % (self.section.section_name, self.regex[1:])
        self.name = '%s.%s' % (self.section.section_name, self.name)
    
    def set_backend_prefix(self, prefix):
        if prefix:
            self.name = prefix + '.' + self.name
    
    def get_url(self):
        return url(self.regex, self.view, {'section': self.section, 'action': self}, name=self.name)


class SectionManager:
    def __init__(self, name, menu_name, page_title):
        self.section_name = name
        self.menu_name = menu_name
        self.page_title = page_title
        self._register = list()
        self.index = None
    
    def set_backend_prefix(self, prefix):
        if prefix:
            self.name = prefix + '.' + self.section_name
        
        for action in self._register:
            action.set_backend_prefix(prefix)
    
    def add_action(self, a):
        if a.is_index:
            self.index = a
        
        a.set_section(self)
        self._register.append(a)
    
    def get_index_url(self):
        if self.index is None:
            self.index = self._register[0]
            
        return url(r'^%s/$' % self.section_name, self.index.view, {'section': self, 'action': self.index}, name=self.name)
    
    def get_urls(self):
        urls = [self.get_index_url()]
        
        for action in self._register:
            urls.append(action.get_url())
        
        return urls
    
    def actions(self):
        return self._register